package com.Nahida.NaHome.service;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;

import androidx.annotation.Nullable;

import com.Nahida.NaHome.R;
import com.Nahida.NaHome.activity.HomeActivity;

import java.util.Timer;
import java.util.TimerTask;

/*
悬浮窗服务
 */
public class FloatService extends Service {

    String type;
    WindowManager windowManager;
    View windowView;
    int screenWidth, screenHeight;
    int windowWidth, windowHeight;
    
    int prevX, prevY;
    boolean moving = false;

    long click_last;

    Timer orientationTimer;
    Handler handler;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public int onStartCommand(Intent serviceIntent, int flags, int startId) {

        if(serviceIntent == null) {
            stopSelf();
            return super.onStartCommand(serviceIntent,flags,startId);
        }

        type = serviceIntent.getStringExtra("type");

        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        getScreenSize();

        handler = new Handler();

        WindowManager.LayoutParams params = new WindowManager.LayoutParams();
        params.format = PixelFormat.TRANSLUCENT;
        params.type = (Build.VERSION.SDK_INT < 26 ? WindowManager.LayoutParams.TYPE_PHONE : WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);

        if(type != null && type.equals("scan")){
            windowView = new View(this);

            //窗口大小位置和参数
            windowWidth = (int) (screenWidth / 6.5f);
            windowHeight = (int) (screenHeight / 6.5f);
            params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;// | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
            params.gravity = Gravity.START | Gravity.TOP;
            params.x = 0;
            params.y = 0;

            windowView.setBackgroundColor(Color.argb(0x10,0xEE,0xFF,0xEE));

            /*
            windowView.setOnKeyListener((view, i, keyEvent) -> {
                if(i == KeyEvent.KEYCODE_BACK && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                    backHome();
                    return true;
                }
                return false;
            });

             */

            windowView.setOnClickListener(view -> backHome());

        }
        else{
            windowView = new View(this);
            windowView.setBackgroundResource(R.mipmap.heart);
            windowHeight = (Math.min(screenHeight, screenWidth)) / 4;
            windowWidth = windowHeight;
            params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
            params.gravity = Gravity.START | Gravity.TOP;
            params.x = screenWidth - (windowWidth / 2);
            params.y = (screenHeight - windowHeight) / 2;

            windowView.setOnTouchListener((view, event) -> {
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:      //按下时，记录点击位置和时间
                        prevX = (int) event.getRawX();
                        prevY = (int) event.getRawY();
                        break;
                    case MotionEvent.ACTION_MOVE:      //移动
                        int nowX = (int) event.getRawX();
                        int nowY = (int) event.getRawY();
                        int moveX = nowX - prevX;
                        int moveY = nowY - prevY;
                        prevX = nowX;
                        prevY = nowY;

                        params.x = params.x + moveX;
                        params.y = params.y + moveY;
                        windowManager.updateViewLayout(view, params);
                        moving = true;
                        break;
                    case MotionEvent.ACTION_UP:      //抬手
                        if(moving){
                            moving = false;
                        }
                        break;
                    default:
                        break;
                }
                return false;
            });

            windowView.setOnClickListener(view -> {
                long click_this = System.currentTimeMillis();
                if(click_this - click_last < 500){
                    backHome();
                }
                else click_last = click_this;
            });
        }
        
        params.width = windowWidth;
        params.height = windowHeight;
        windowManager.addView(windowView, params);

        orientationTimer = new Timer();
        orientationTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                handler.post(()->{
                    try {
                        getScreenSize();
                        if (params.x < 0) params.x = 0;
                        if (params.x > screenWidth) params.x = screenWidth;
                        if (params.y < 0) params.y = 0;
                        if (params.y > screenHeight) params.y = screenHeight;
                        if (windowView != null) windowManager.updateViewLayout(windowView, params);
                    }catch (Exception e){
                        e.printStackTrace();
                        this.cancel();
                        backHome();
                    }
                });
            }
        },1000,2000);

        return super.onStartCommand(serviceIntent, flags, startId);
    }

    @Override
    public void onDestroy() {
        if(windowView!=null) windowManager.removeView(windowView);
        if(orientationTimer!=null) orientationTimer.cancel();
        Log.d("debug-FloatService", "onDestroy");
        super.onDestroy();
    }

    public void backHome(){
        Intent intent = new Intent(this, HomeActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        this.stopSelf();
    }

    public void getScreenSize(){
        DisplayMetrics displayMetrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getRealMetrics(displayMetrics);
        screenWidth = displayMetrics.widthPixels;
        screenHeight = displayMetrics.heightPixels;
        Log.d("debug-orientation",screenWidth + "x"+ screenHeight);
    }
}
